import requests
import time
import json
import re
import asyncio
from datetime import datetime

from .pb_config import PB_Config as config
from data.crawler_data import Game_Info, Game_Odds, flag_dict

class PB:
    def __init__(self):
        self.url = "https://www.pin975.com/sports-service/sv/compact/events"
        self.url_other = "https://www.pin975.com/sports-service/sv/compact/outright"
    
    def get_login_uid(self, xml_str = None):
        """登录并从返回的xml中解析出uid"""
        pass
    
    def query_football_today_lid(self, btg, hle, mk):
        """抓比赛数据, 直接获取今日所有比赛的me"""
        # 设置今日请求参数
        config.football_request['btg'] = btg
        config.football_request['hle'] = hle
        config.football_request['mk'] = mk
        config.football_request['_'] = str(int(time.time() * 1000))
        # 获取今日初盘返回的xml响应
        response = requests.get(self.url, headers=config.headers, cookies=config.cookies, params=config.football_request)
        # 解析出所有me_id
        root = json.loads(response.text)
        results = []
        datas = root['n'][0][2]
        for data in datas:
            games = data[2]
            # games = data.get(2, [])
            for game in games:
                odds = []
                gameInfo = Game_Info()
                gameInfo.game_odds = odds
                
                # 因为获取详情没有当前比赛的独赢, 所以从这里就开始弄
                # 开始时间时间戳装换
                kick_off_time = self.parseJson(4, game)    # 开赛时间
                kick_off_time = int(kick_off_time) / 1000.0
                dt = datetime.fromtimestamp(kick_off_time)
                formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S')
                gameInfo.kick_off_time = formatted_time         # 开赛时间
                gameInfo.team_id = self.parseJson(0, game)   # 赛事id
                gameInfo.league = self.parseJson(1, data)    # 联赛
                gameInfo.source = "平博"                     # 数据来源
                team_h = self.parseJson(1, game)
                team_c = self.parseJson(2, game)
                if '主队' in team_h and '客队' in team_c:
                    continue
                team = team_h + ' vs ' + team_c
                gameInfo.team_home = team_h         # 主队
                gameInfo.team_away = team_c         # 客队
                gameInfo.team = team                # 对战
                
                # 赔率
                full = game[8].get('0', None)                 # 全场
                full = full[0] if full else None
                falf = game[8].get('1', None)                 # 半场
                falf = falf[0] if falf else None
                
                # 独赢
                odds.append(Game_Odds('win_h', self.parseJson(1, full), flag_dict.get('win_h'), team_h))    # 主队 胜 - 赔率
                odds.append(Game_Odds('win_c', self.parseJson(2, full), flag_dict.get('win_c'), team_c))    # 客队 胜 - 赔率
                odds.append(Game_Odds('win_n', self.parseJson(0, full), flag_dict.get('win_n')))        # 平局 - 赔率
                
                # 独赢 - 半场
                odds.append(Game_Odds('win_h_half', self.parseJson(1, falf), flag_dict.get('win_h_half'), team_h))  # 主队 胜 (半场) - 赔率
                odds.append(Game_Odds('win_c_half', self.parseJson(2, falf), flag_dict.get('win_c_half'), team_c))  # 客队 胜 (半场) - 赔率
                odds.append(Game_Odds('win_n_half', self.parseJson(0, falf), flag_dict.get('win_n_half')))      # 平局 (半场) - 赔率

                results.append(gameInfo)
        return results

    async def get_football_detail(self, hle, game):
        """获取今日初盘的足球数据"""
        await asyncio.sleep(3)
        # 设置今日请求参数
        config.football_request_detail['me'] = game.team_id
        config.football_request_detail['hle'] = hle
        config.football_request_detail['_'] = str(int(time.time() * 1000))
        # 获取今日初盘返回的xml响应
        response = requests.get(self.url, headers=config.headers_detail, cookies=config.cookies_detail, params=config.football_request_detail, verify=False)
        # 解析单场球赛所有数据
        return self.parseData_detail(response.text, game)

    def parseData_detail(self, xml_str, gameInfo):
        """解析比赛"""
        odds = gameInfo.game_odds
        root = None
        if xml_str is None:
            with open('./pingB/比赛.json', 'r', encoding='utf-8') as file:
                root = json.load(file)
        else:
            root = json.loads(xml_str)
        if root["be"] is None:
            return gameInfo
        datas = root["be"][3][8]
        
        # 罚牌数大小
        cards = datas.get('0', None)
        cards = cards[3] if cards is not None else []
        for card in cards:
            card_big_flag = self.parseJson(0, card)      # 大 - 标识
            card_small_flag = self.parseJson(0, card)    # 小 - 标识
            odds.append(Game_Odds(card_big_flag, 'card_big', self.parseJson(2, card), '罚牌数大小', f'大{card_big_flag}'))       # 大 - 赔率
            odds.append(Game_Odds(card_small_flag, 'card_small', self.parseJson(3, card), '罚牌数大小', f'小{card_small_flag}')) # 小 - 赔率
        return gameInfo

    def query_football_today(self, btg, hle, mk):
        """获取今日初盘的足球数据"""
        # 设置早盘请求参数
        config.football_request['btg'] = btg
        config.football_request['hle'] = hle
        config.football_request['mk'] = mk
        config.football_request_other['_'] = str(int(time.time() * 1000))
        # 获取今日初盘返回的xml响应
        response = requests.get(config.url, headers=config.headers, cookies=config.cookies, params=config.football_request)
        if btg == "1" and hle == "false" and mk == "1":
            print(f"已获取 平博 今日 [比赛]")
            return self.parseData_match(response.text)

    def query_football_other(self, ort, mk):
        """获取今日初盘的足球数据"""
        # 设置早盘请求参数
        config.football_request_other['ort'] = ort
        config.football_request_other['mk'] = mk
        config.football_request_other['_'] = str(int(time.time() * 1000))
        # 获取今日初盘返回的xml响应
        response = requests.get(config.url_other, headers=config.headers, cookies=config.cookies, params=config.football_request_other)
        if ort == "2" and mk == "1":
            print(f"已获取 平博 今日 [特别投注]")
            return self.parseData_special(response.text)
        elif ort == "4" and mk == "1":
            print(f"已获取 平博 今日 [双重机会]")
            return self.parseData_dc(response.text)

    def parseData_match(self, xml_str):
        """解析比赛"""
        root = None
        root = json.loads(xml_str)
        datas = root["n"][0][2]
        results = []
        for data in datas:
            games = data[2]
            for game in games:
                odds = []
                gameInfo = Game_Info()
                gameInfo.game_odds = odds
                
                # league_en = self.parseJson(4, data)
                gameInfo.league = self.parseJson(1, data)   # 联赛
                gameInfo.league_en = self.parseJson(4, data)   # 联赛
                gameInfo.source = "平博"                     # 数据来源
                
                gameInfo.team_id = self.parseJson(0, game)         # 比赛id
                # 开始时间时间戳装换
                kick_off_time = self.parseJson(4, game)    # 开赛时间
                kick_off_time = int(kick_off_time) / 1000.0
                dt = datetime.fromtimestamp(kick_off_time)
                formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S')
                gameInfo.kick_off_time = formatted_time         # 开赛时间
                team_h = self.parseJson(1, game)
                team_c = self.parseJson(2, game)
                team_h_en = self.parseJson(24, game)
                team_c_en = self.parseJson(25, game)
                if '主队' in team_h and '客队' in team_c:
                    continue
                team = team_h + ' vs ' + team_c
                team_en = team_h_en + ' vs ' + team_c_en
                gameInfo.team_home = team_h             # 主队
                gameInfo.team_h_en = team_h_en          # 主队
                gameInfo.team_away = team_c             # 客队
                gameInfo.team_c_en = team_c_en          # 客队
                gameInfo.team = team                    # 对战
                gameInfo.team_en = team_en                # 对战
                # print(f" >>> {gameInfo.team_id} | {gameInfo.league} | {gameInfo.team}")
                
                # 赔率
                full = game[8].get('0')                # 全场
                falf = game[8].get('1')
                
                # 独赢
                if None != full:
                    odds.append(Game_Odds('win_h', self.parseJson(1, full[2]), flag_dict.get('win_h'), team_h))    # 主队 胜 - 赔率
                    odds.append(Game_Odds('win_c', self.parseJson(0, full[2]), flag_dict.get('win_c'), team_c))    # 客队 胜 - 赔率
                    odds.append(Game_Odds('win_n', self.parseJson(2, full[2]), flag_dict.get('win_n')))        # 平局 - 赔率
                
                # 独赢 - 半场
                if None != falf:
                    odds.append(Game_Odds('win_h_half', self.parseJson(1, falf[2]), flag_dict.get('win_h_half'), team_h))  # 主队 胜 (半场) - 赔率
                    odds.append(Game_Odds('win_c_half', self.parseJson(0, falf[2]), flag_dict.get('win_c_half'), team_c))  # 客队 胜 (半场) - 赔率
                    odds.append(Game_Odds('win_n_half', self.parseJson(2, falf[2]), flag_dict.get('win_n_half')))      # 平局 (半场) - 赔率
                
                # 让球
                rcs = full[0]
                for rc in rcs:
                    ratio = rc[2]
                    strong_home = 'ud_h'
                    strong_away = 'ud_c'
                    if '-' in str(rc[1]) and '-' not in str(rc[1]):
                        strong_home = 'hcap_h'
                    else:
                        strong_away = 'hcap_c'
                    odds.append(Game_Odds(strong_home+'_'+str(ratio).replace("-", "/"), self.parseJson(3, rc), flag_dict.get(strong_home), f'{team_h},{ratio}'))  # 主队让球 - 赔率
                    odds.append(Game_Odds(strong_away+'_'+str(ratio).replace("-", "/"), self.parseJson(4, rc), flag_dict.get(strong_away), f'{team_c},{ratio}'))  # 客队让球 - 赔率
                
                results.append(gameInfo)
        return results

    def parseData_special(self, xml_str):
        """解析比赛"""
        # odds = gameInfo.game_odds
        root = None
        if xml_str is None:
            with open('./pingB/特别投注.json', 'r', encoding='utf-8') as file:
                root = json.load(file)
        else:
            root = json.loads(xml_str)
        games = root["a"]
        results = []
        for game in games:
            if game['cg'] == '球员主题投注':
                continue
            odds = []
            gameInfo = Game_Info()
            gameInfo.game_odds = odds
            
            gameInfo.league = self.parseJson('ln', game)
            gameInfo.team_id = self.parseJson('ei', game['se'][0])
            team = self.parseJson('levn', game)
            teams = team.split()
            gameInfo.team_home = teams[0]
            gameInfo.team_away = teams[2]
            gameInfo.team = teams[0] + ' vs ' + teams[2]
            # print(f" >>> {gameInfo.team_id} | {gameInfo.league} | {gameInfo.team}")
            handicaps = game['se']
            for handicap in handicaps:
                if handicap.get('n', None) == '两队都得分？':           # 双方球队进球
                    for l in handicap['l']:
                        if l.get('n') == "是":
                            odds.append(Game_Odds('btts_y', self.parseJson('p', l), flag_dict.get('btts_y')))   # 是 - 赔率
                        elif l.get('n') == "否":
                            odds.append(Game_Odds('btts_n', self.parseJson('p', l), flag_dict.get('btts_n')))   # 是 - 赔率
                elif handicap.get('n', None) == '两队都得分？上半场':   #双方球队进球 - 半场
                    for l in handicap['l']:
                        if l.get('n') == "是":
                            odds.append(Game_Odds('btts_y_half', self.parseJson('p', l), flag_dict.get('btts_y_half'))) # 是 - 赔率 (半场)
                        elif l.get('n') == "否":
                            odds.append(Game_Odds('btts_n_half', self.parseJson('p', l), flag_dict.get('btts_n_half'))) # 是 - 赔率 (半场)
                elif handicap.get('n', None) == '两队得分/总进球数':         #大/小 & 双方球队进球
                    for l in handicap['l']:
                        if "是且大盘" in l.get('n'):
                            ratio = l.get('n')[l.get('n').find(' ')+1:]
                            odds.append(Game_Odds('over_btts_y', self.parseJson('p', l), flag_dict.get('over_btts_y'), ratio))  # 大 & 是 (ratio) - 赔率
                        elif "否且大盘" in l.get('n'):
                            ratio = l.get('n')[l.get('n').find(' ')+1:]
                            odds.append(Game_Odds('over_btts_n'+'_'+str(ratio), self.parseJson('p', l), flag_dict.get('over_btts_n'), ratio))  # 大 & 否 (fratiolag) - 赔率
                        elif "是且小盘" in l.get('n'):
                            ratio = l.get('n')[l.get('n').find(' ')+1:]
                            odds.append(Game_Odds('under_btts_y'+'_'+str(ratio), self.parseJson('p', l), flag_dict.get('under_btts_y'), ratio))    # 小 & 是 (ratio) - 赔率
                        elif "否且小盘" in l.get('n'):
                            ratio = l.get('n')[l.get('n').find(' ')+1:]
                            odds.append(Game_Odds('under_btts_n'+'_'+str(ratio), self.parseJson('p', l), flag_dict.get('under_btts_n'), ratio))    # 小 & 否 (ratio) - 赔率
                elif handicap.get('n', None) == '两队得分/胜者':    # 独赢 & 双方球队进球
                    for l in handicap['l']:
                        if gameInfo.team_home in l.get('n') and '是和' in l.get('n'):
                            odds.append(Game_Odds('win_btts_h_y', self.parseJson('p', l), flag_dict.get('win_btts_h_y'), gameInfo.team_home))   # 主队 & 是 - 赔率
                        elif gameInfo.team_home in l.get('n') and '否和' in l.get('n'):
                            odds.append(Game_Odds('win_btts_h_n', self.parseJson('p', l), flag_dict.get('win_btts_h_n'), gameInfo.team_home))   # 主队 & 否 - 赔率
                        elif gameInfo.team_away in l.get('n') and '是和' in l.get('n'):
                            odds.append(Game_Odds('win_btts_c_y', self.parseJson('p', l), flag_dict.get('win_btts_c_y'), gameInfo.team_away))   # 客队 & 是 - 赔率
                        elif gameInfo.team_away in l.get('n') and '否和' in l.get('n'):
                            odds.append(Game_Odds('win_btts_c_n', self.parseJson('p', l), flag_dict.get('win_btts_c_n'), gameInfo.team_away))   # 客队 & 否 - 赔率
                        elif '是且平局' in l.get('n'):
                            odds.append(Game_Odds('win_btts_n_y', self.parseJson('p', l), flag_dict.get('win_btts_n_y')))   # 平局 & 是 - 赔率
                        elif '否且平局' in l.get('n'):
                            odds.append(Game_Odds('win_btts_n_n', self.parseJson('p', l), flag_dict.get('win_btts_n_n')))   # 平局 & 否 - 赔率
                elif handicap.get('n', None) == '正确得分':
                    for l in handicap['l']:
                        flag = l.get('n').split(', ')
                        flag_h = flag[0].split(' ')
                        flag_c = flag[1].split(' ')
                        flag = flag_h[1] +':'+ flag_c[1]
                        if '0:0' == flag:
                            odds.append(Game_Odds('zero_zero', self.parseJson('p', l), flag_dict.get('zero_zero'))) # 0:0 - 赔率
                        elif '1:1' == flag:
                            odds.append(Game_Odds('one_one', self.parseJson('p', l), flag_dict.get('one_one'))) # 1:1 - 赔率
                elif handicap.get('n', None) == f'{gameInfo.team_home}零封对手？':
                    for l in handicap['l']:
                        if "是" in l.get('n'):
                            odds.append(Game_Odds('cs_win_h', self.parseJson('p', l), flag_dict.get('cs_win_h'), gameInfo.team_home))   # 主队 零失球获胜 - 赔率
                        elif "否" in l.get('n'):
                            pass
                elif handicap.get('n', None) == f'{gameInfo.team_away}零封对手？':
                    for l in handicap['l']:
                        if "是" in l.get('n'):
                            odds.append(Game_Odds('cs_win_c', self.parseJson('p', l), flag_dict.get('cs_win_c'), gameInfo.team_away))   # 客队 零失球获胜 - 赔率
                        elif "否" in l.get('n'):
                            pass
                elif handicap.get('n', None) == '还没想好继续抓啥':
                    pass
        
            results.append(gameInfo)
        return results

    def parseData_dc(self, xml_str):
        """解析比赛"""
        # odds = gameInfo.game_odds
        root = None
        root = json.loads(xml_str)
        games = root["a"]
        results = []
        for game in games:
            odds = []
            gameInfo = Game_Info()
            gameInfo.game_odds = odds
            
            gameInfo.league = self.parseJson('ln', game)
            gameInfo.team_id = self.parseJson('parentId', game)
            team = self.parseJson('levn', game)
            teams = team.split()
            gameInfo.team_home = teams[0]
            gameInfo.team_away = teams[2]
            gameInfo.team = teams[0] + ' vs ' + teams[2]
            # print(f" >>> {gameInfo.team_id} | {gameInfo.league} | {gameInfo.team}")
            handicaps = game['se']
            full = handicaps[0] if len(handicaps) > 0 else None
            half = handicaps[1] if len(handicaps) > 1 else None
            if full is not None:
                for l in full['l']:
                    if re.sub(r"\s", "", l['n']) == f'{gameInfo.team_home}或平局':
                        odds.append(Game_Odds('dc_h_n', self.parseJson('p', l), flag_dict.get('dc_h_n'), gameInfo.team_home))   # 主队 | 平局 - 赔率
                    elif re.sub(r"\s", "", l['n']) == f'平局或{gameInfo.team_away}':
                        odds.append(Game_Odds('dc_c_n', self.parseJson('p', l), flag_dict.get('dc_c_n'), gameInfo.team_away))   # 客队 | 平局 - 赔率
                    elif re.sub(r"\s", "", l['n']) == f'{gameInfo.team_home}或{gameInfo.team_away}':
                        odds.append(Game_Odds('dc_h_c', self.parseJson('p', l), flag_dict.get('dc_h_c'), f'{gameInfo.team_home},{gameInfo.team_away}'))   # 主队 | 客队 - 赔率
            results.append(gameInfo)
        return results

    def parseJson(self, node, json):
        if json is None:
            return None
        value = str(json[node])
        if value is not None:
            return re.sub(r"[\n\t\r]", "", value)
        else:
            return None



if __name__ == "__main__":
    pb = PB()
    xml_str = """<?xml version="1.0" encoding="UTF-8" ?>
        <serverresponse>
        <status>200</status>
        <msg>100</msg>
        <code_message></code_message>
        <username>ckbv577</username>
        <mid>37000065</mid>
        <uid>616goerzm37000065l55226b0</uid>
        <passwd_safe>Goblin9527</passwd_safe>
        <ltype>3</ltype>
        <currency>RMB</currency>
        <odd_f>H,M,I,E</odd_f>
        <pay_type>0</pay_type>
        <blackBoxStatus>N</blackBoxStatus>
        <domain>199.26.100.165</domain>
        <t_link>BAD</t_link>
        </serverresponse>
    """
    is_uid = pb.get_login_uid(xml_str)
    print(f"-------------------->>> uid: {config.uid}")
    if True:
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        # 今日 比赛/过关
        pb.query_football("1", "false", "1")
        # 今日 输赢盘(半场&全场)
        # pb.query_football("2", "false", "1")
        # 今日 球队总得分
        # pb.query_football("100", "false", "1")
        # 今日 特别投注
        # pb.query_football_other("2", "1")
        # 今日 双重机会
        # pb.query_football_other("4", "1")
        
        # 早盘 比赛/过关
        # pb.query_football("1", "true", "0")
        # 早盘 输赢盘(半场&全场)
        # pb.query_football("2", "true", "0")
        # 早盘 输赢盘(半场&全场)
        # pb.query_football("100", "true", "0")
        # 早盘 特别投注
        # pb.query_football_other("2", "0")
        # 早盘 双重机会
        # pb.query_football_other("4", "0")
